package com.shxy.cloudclassroom.controller.common;

import com.shxy.cloudclassroom.entity.pojo.User;
import com.shxy.cloudclassroom.entity.dto.UserDTO;
import com.shxy.cloudclassroom.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

import static com.shxy.cloudclassroom.utils.SystemConstant.*;

/**
 * @Author 吴汇明
 * @School 绥化学院
 * @CreateTime 2025.10.20
 * 登录验证模块
 */
@RequestMapping("/common")
@Controller
public class LoginController {
    @Resource
    private UserService userService;

    /**
     * 登录功能
     *
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public ResponseEntity<String> login(@RequestBody UserDTO userDTO, HttpSession session) {
        System.out.println("common login ...");
        try {
            User user = userService.login(userDTO, session);
            // 如果登录成功，保存用户信息
            if (user != null) {
                System.out.println(user);
                session.setAttribute(LOGIN_USER, user);
                session.setAttribute(USER_IDENTITY,user.getRole());
                //设置有效期
                session.setMaxInactiveInterval(LOGIN_USER_TTL);
                return ResponseEntity.ok("ok");
            } else {
                // 登录失败，返回错误信息
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名或密码错误");
            }
        } catch (Exception e) {
            // 登录异常，返回错误信息
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
        }
    }
}
